<template>
  <ElForm class="drawer-detail" label-width="100px" label-position="left">
    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center">
      <div class="drawer-detail-header">
        <div class="drawer-detail-header-title">{{ data.customerName }}</div>
<!--        <div class="drawer-detail-header-sub">客户ID: {{ data.customerNo }}</div>-->
      </div>
      <div>
        <ElButton type="danger" @click="toDispatchGroupExistingShow">选择已有分组</ElButton>
        <ElButton type="primary" @click="toDispatchGroupShow">分配</ElButton>
        <ElButton v-if="props.row?.feeModel === 0 && activeName !== '单独收费' && activeName !== '待分配'" type="primary" @click="onEditGroup">编辑分组</ElButton>
      </div>
    </div>

    <!--    {{Object.keys(groupShopInfos)}}-->
    <!--    {{checkList}}-->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="checkShopIdList = []">
      <el-tab-pane v-for="(item, index) in Object.keys(groupShopInfos)" :key="index" :label="item" :name="item">
        <div  v-if="activeName !== '单独收费' && activeName !== '待分配'">
<!--          <div>底薪: {{groupShopInfos[item] ? groupShopInfos[item][0].baseSalary : 0 }}</div>-->
          <div>底薪: {{ groupShopInfos[item][0] ? groupShopInfos[item][0]?.baseSalary : 0}}</div>
        </div>
        <div class="drawer-detail-body">
          <div
              v-for="(item, index) in groupShopInfos[item]"
              :key="index"
              class="drawer-detail-card"
              style="display: flex; flex-direction: row; align-items: baseline"
          >
            <el-checkbox-group v-model="checkShopIdList" v-if="activeName !== '单独收费'">
              <el-checkbox :value="item.shopId"/>
            </el-checkbox-group>

            <div>
              <div class="drawer-detail-card-header">
<!--                <div class="drawer-detail-card-title">{{ item.shopNo }}-{{ item.shopName }}</div>-->
                <div class="drawer-detail-card-title">{{ item.shopName }}</div>
                <div>
                  <ElButton link type="primary" @click="$emit('edit-shop', props.row)">编辑</ElButton>
                  <ElButton link type="primary" @click="$emit('stop-cooperation', props.row)">停止合作</ElButton>
                  <ElButton link type="primary" @click="$emit('stop-notice', props.row)">到期通知</ElButton>
                  <ElButton link type="primary" @click="$emit('copy', props.row)">复制</ElButton>
                  <ElButton link type="primary" @click="$emit('change-log', props.row)">改动记录</ElButton>
                </div>
              </div>

              <ElRow>
                <ElCol :span="6">
                  <ElFormItem label="平台">{{ item.platformName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="店铺类型">{{ item.shopTypeName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="客服类型">{{ item.customTypeName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="服务班次">{{ item.serviceShiftName }}</ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem label="底薪">{{ item.baseSalary }} <span v-if="item.feeModel === 0">(合并)</span></ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="提成">{{ item.commission }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="咨询人数">{{ item.consultPeopleNum }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="服务天数"></ElFormItem>
                </ElCol>

                <template v-if="item.expand">
                  <ElCol :span="6">
                    <ElFormItem label="合作状态">{{ getCooperateStatus(item.cooperateStatus) }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="拓客渠道">{{ item.expandTypeName }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="店铺链接">{{ item.shopLinkUrl }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="店铺地址"></ElFormItem>
                  </ElCol>

                  <ElCol :span="6">
                    <ElFormItem label="营销类型">{{ item.marketTypeName }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="剔除退款">{{ getExcludingRefunds(item.excludingRefunds) }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="转化率">{{ item.conversionRate }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="开始日期">{{ item.startDate }}</ElFormItem>
                  </ElCol>

                  <ElCol :span="6">
                    <ElFormItem label="截止日期">{{ item.endDate }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="联系人姓名">{{ item.contacts }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="联系方式">
                      <div v-if="item.phone">手机/{{ item.phone }}</div>
                      <div v-if="item.wechat">微信/{{ item.wechat }}</div>
                      <div v-if="item.qq">QQ/{{ item.qq }}</div>
                      <div v-if="item.ding">钉钉/{{ item.ding }}</div>
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="响应时间">{{ item.responseSecond }}</ElFormItem>
                  </ElCol>

                  <ElCol :span="6">
                    <ElFormItem label="特别备注">{{ item.customerServiceMessage }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="备注">{{ item.remark }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="客户配合度">{{ item.fitRatioName }}</ElFormItem>
                  </ElCol>
                  <ElCol :span="6">
                    <ElFormItem label="店铺对接人">{{ item.storeLiaison }}</ElFormItem>
                  </ElCol>
                </template>
              </ElRow>

              <ElButton v-if="item.expand" link type="primary" @click="item.expand = false">收起全部信息
                <el-icon>
                  <ArrowUp/>
                </el-icon>
              </ElButton>
              <ElButton v-if="!item.expand" link type="primary" @click="item.expand = true">查看全部信息
                <el-icon>
                  <ArrowDown/>
                </el-icon>
              </ElButton>
            </div>
          </div>
          <ElEmpty v-if="!groupShopInfos[item] || !groupShopInfos[item].length"/>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!--    <div class="drawer-detail-body">

          <div
              v-for="(item, index) in data.shopList"
              :key="index"
              class="drawer-detail-card"
          >
            <div class="drawer-detail-card-header">
              <div class="drawer-detail-card-title">{{ item.shopNo }}-{{ item.shopName }}</div>
              <div>
                <ElButton link type="primary" @click="$emit('edit-shop', props.row)">编辑</ElButton>
                <ElButton link type="primary" @click="$emit('stop-cooperation', props.row)">停止合作</ElButton>
                <ElButton link type="primary" @click="$emit('stop-notice', props.row)">到期通知</ElButton>
                <ElButton link type="primary" @click="$emit('copy', props.row)">复制</ElButton>
                <ElButton link type="primary" @click="$emit('change-log', props.row)">改动记录</ElButton>
              </div>
            </div>

            <ElRow>
              <ElCol :span="6">
                <ElFormItem label="平台">{{ item.platformName }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="店铺类型">{{ item.shopTypeName }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="客服类型">{{ item.customTypeName }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="服务班次">{{ item.serviceShiftName }}</ElFormItem>
              </ElCol>

              <ElCol :span="6">
                <ElFormItem label="底薪">{{ item.baseSalary }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="提成">{{ item.commission }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="咨询人数">{{ item.consultPeopleNum }}</ElFormItem>
              </ElCol>
              <ElCol :span="6">
                <ElFormItem label="服务天数"></ElFormItem>
              </ElCol>

              <template v-if="item.expand">
                <ElCol :span="6">
                  <ElFormItem label="合作状态">{{ getCooperateStatus(item.cooperateStatus) }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="拓客渠道">{{ item.expandTypeName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="店铺链接">{{ item.shopLinkUrl }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="店铺地址"></ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem label="营销类型">{{ item.marketTypeName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="剔除退款">{{ getExcludingRefunds(item.excludingRefunds) }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="转化率">{{ item.conversionRate }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="开始日期">{{ item.startDate }}</ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem label="截止日期">{{ item.endDate }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="联系人姓名">{{ item.contacts }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="联系方式">
                    <div v-if="item.phone">手机/{{ item.phone }}</div>
                    <div v-if="item.phone">微信/{{ item.wechat }}</div>
                    <div v-if="item.phone">QQ/{{ item.qq }}</div>
                    <div v-if="item.phone">钉钉/{{ item.ding }}</div>
                  </ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="响应时间">{{ item.responseSecond }}</ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem label="特别备注">{{ item.customerServiceMessage }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="备注">{{ item.remark }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="客户配合度">{{ item.fitRatioName }}</ElFormItem>
                </ElCol>
                <ElCol :span="6">
                  <ElFormItem label="店铺对接人">{{ item.storeLiaison }}</ElFormItem>
                </ElCol>
              </template>
            </ElRow>

            <ElButton v-if="item.expand" link type="primary" @click="item.expand = false">收起全部信息
              <el-icon>
                <ArrowUp/>
              </el-icon>
            </ElButton>
            <ElButton v-if="!item.expand" link type="primary" @click="item.expand = true">查看全部信息
              <el-icon>
                <ArrowDown/>
              </el-icon>
            </ElButton>
          </div>
          <ElEmpty v-if="!data.shopList || !data.shopList.length"/>
        </div>-->
  </ElForm>

  <el-dialog v-model="dispatchGroupVisible" title="分配" width="500">
    <el-form :model="customerManagementDispatchGroupQuery" :rules="dispatchGroupRules" ref="dispatchGroupFormRef">
      <el-form-item label="分组名称" label-width="80px" prop="mergeGroup">
        <el-input v-model="customerManagementDispatchGroupQuery.mergeGroup" autocomplete="off"
                  placeholder="请填写分组名称"/>
      </el-form-item>
      <el-form-item label="底薪" label-width="80px" prop="baseSalary">
        <el-input-number v-model="customerManagementDispatchGroupQuery.baseSalary" controls-position="right"
                         placeholder="请填写底薪"/>
        <!--        <el-input v-model="customerManagementDispatchGroupQuery.baseSalary" type="number" placeholder="请填写底薪"/>-->
      </el-form-item>
      <!--      <el-form-item>
              &lt;!&ndash;        <el-button type="primary" @click="onSubmit">Create</el-button>&ndash;&gt;
              &lt;!&ndash;        <el-button>Cancel</el-button>&ndash;&gt;
              <el-button @click="dispatchGroupVisible = false">取消</el-button>
              <el-button type="primary" @click="onSubmit">
                确定
              </el-button>
            </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dispatchGroupVisible = false">取消</el-button>
        <el-button @click="resetDispatchGroupForm">重置</el-button>
        <el-button type="primary" @click="onSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="dispatchGroupExistingVisible" title="选择已有分组" width="500">
    <el-form :model="customerManagementDispatchGroupExistingQuery" :rules="dispatchGroupExistingRules"
             ref="dispatchGroupFormExistingRef">
      <el-form-item label="分组名称" label-width="80px" prop="mergeGroup">
        <!--        <el-input v-model="customerManagementDispatchGroupExistingQuery.mergeGroup" autocomplete="off"
                          placeholder="请填写分组名称"/>-->
        <el-select v-model="customerManagementDispatchGroupExistingQuery.mergeGroup" placeholder="请选择已有分组">
          <el-option
              v-for="item in groupList"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="底薪" label-width="80px" prop="baseSalary">-->
<!--        <el-input-number v-model="customerManagementDispatchGroupExistingQuery.baseSalary" controls-position="right"-->
<!--                         placeholder="请填写底薪"/>-->
<!--        &lt;!&ndash;        <el-input v-model="customerManagementDispatchGroupQuery.baseSalary" type="number" placeholder="请填写底薪"/>&ndash;&gt;-->
<!--      </el-form-item>-->
      <!--      <el-form-item>
              &lt;!&ndash;        <el-button type="primary" @click="onSubmit">Create</el-button>&ndash;&gt;
              &lt;!&ndash;        <el-button>Cancel</el-button>&ndash;&gt;
              <el-button @click="dispatchGroupVisible = false">取消</el-button>
              <el-button type="primary" @click="onSubmit">
                确定
              </el-button>
            </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dispatchGroupExistingVisible = false">取消</el-button>
        <el-button @click="resetDispatchGroupExistingForm">重置</el-button>
        <el-button type="primary" @click="onDispatchGroupExistingSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import {cooperateStatusOptions, excludingRefundsOptions} from '../constant'
import {ArrowUp, ArrowDown} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import {
  getCustomerManagementDispatchGroup,
  getCustomerManagementGroupList,
  getCustomerManagementGroupShopInfo,
  updateGroupShopInfo
} from "@/views/menus/customer-management/api.ts";
import {ElButton, ElMessage, FormRules} from "element-plus";
import { changeGroupDialog } from '../dialog/changeGroupDialog'

interface Props {
  row: any
}

const props = withDefaults(defineProps<Props>(), {
  row: () => ({})
})

const data = props.row || {}

const getCooperateStatus = (val) => {
  const d = cooperateStatusOptions.find(v => v.value === val)
  return d && d.label
}

const getExcludingRefunds = (val) => {
  const d = excludingRefundsOptions.find(v => v.value === val)
  return d && d.label
}


/**
 * 复选框
 */
const checkShopIdList = ref([])

const customerManagementGroupShopInfoQuery = ref({
  customerId: data.customerId
})
const activeName = ref('待分配')

const groupShopInfos = ref([])
const groupList = ref([])
async function init() {
  groupShopInfos.value = await getCustomerManagementGroupShopInfo(customerManagementGroupShopInfoQuery.value);
  groupList.value = await getCustomerManagementGroupList(customerManagementGroupShopInfoQuery.value);
}
onMounted(async () => {
  await init()
  // console.log('groupShopInfos', groupShopInfos.value, groupList);
})

/**
 * 分配
 */
const dispatchGroupFormRef = ref()
const dispatchGroupRules = reactive({
  mergeGroup: [
    {required: true, message: '请输入组合名称', trigger: 'blur'},
  ],
  baseSalary: [
    {
      required: true,
      message: '请填写底薪',
      trigger: 'blur',
    },
  ],
})

const dispatchGroupVisible = ref(false)
const customerManagementDispatchGroupQuery = ref({
  customerId: data.customerId,
  shopIds: checkShopIdList,
  mergeGroup: null,
  baseSalary: null
})

// getCustomerManagementDispatchGroup(customerManagementDispatchGroupQuery.value)

const toDispatchGroupShow = () => {
  if (checkShopIdList.value.length <= 0) {
    ElMessage({
      message: '请先选择店铺名称',
      type: 'warning',
    })
  } else {
    dispatchGroupVisible.value = true
  }
}

const onSubmit = async () => {
  console.log('submit!')
  if (!dispatchGroupFormRef.value) return
  await dispatchGroupFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', customerManagementDispatchGroupQuery.value)
      await getCustomerManagementDispatchGroup(customerManagementDispatchGroupQuery.value)
      init()
      dispatchGroupVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetDispatchGroupForm = () => {
  if (!dispatchGroupFormRef.value) return
  dispatchGroupFormRef.value.resetFields()
}

/**
 * 分配已有的
 */
const dispatchGroupFormExistingRef = ref()
const dispatchGroupExistingRules = reactive({
  mergeGroup: [
    {required: true, message: '请选择已有组合', trigger: 'blur'},
  ],
  // baseSalary: [
  //   {
  //     required: true,
  //     message: '请填写底薪',
  //     trigger: 'blur',
  //   },
  // ],
})

const dispatchGroupExistingVisible = ref(false)
const customerManagementDispatchGroupExistingQuery = ref({
  customerId: data.customerId,
  shopIds: checkShopIdList,
  mergeGroup: null,
})

// getCustomerManagementDispatchGroup(customerManagementDispatchGroupQuery.value)

const toDispatchGroupExistingShow = () => {
  if (checkShopIdList.value.length <= 0) {
    ElMessage({
      message: '请先选择店铺名称',
      type: 'warning',
    })
  } else {
    dispatchGroupExistingVisible.value = true
  }
}

const onDispatchGroupExistingSubmit = async () => {
  if (!dispatchGroupFormExistingRef.value) return
  await dispatchGroupFormExistingRef.value.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', customerManagementDispatchGroupExistingQuery.value)
      await getCustomerManagementDispatchGroup(customerManagementDispatchGroupExistingQuery.value)
      init()
      dispatchGroupExistingVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetDispatchGroupExistingForm = () => {
  if (!dispatchGroupFormExistingRef.value) return
  dispatchGroupFormExistingRef.value.resetFields()
}

const onEditGroup = async () => {
  const activeData = groupShopInfos.value[activeName.value]
  if (activeData) {
    const data = await changeGroupDialog.open({
      row: {
        mergeGroup: activeName.value,
        baseSalary: activeData[0] ? activeData[0].baseSalary: 0,
        shopIds: activeData.map(i => i.shopId)
      }
    })
    await updateGroupShopInfo(data)
    init()
  }
}

</script>

<style scoped lang="scss">
.drawer-detail {
  padding: 20px;

  &-header {
    padding-bottom: 20px;
    border-bottom: 1px solid #E1E1E1;
  }

  &-header-title {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 15px;
    color: #333333;
    margin-bottom: 4px;
  }

  &-header-sub {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 12px;
    color: #666666;
  }

  &-card {
    border-bottom: 1px solid #E1E1E1;
    padding-bottom: 14px;
  }

  &-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 15px 0 13px
  }

  :deep(.el-form-item) {
    margin-bottom: 0;
  }

  :deep(.el-form-item__label) {
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 12px;
    color: #666666;
    text-align: right;
  }

  :deep(.el-form-item__content) {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 12px;
    color: #333333;
  }
}
</style>
